<template>
  <!-- 图文资讯详细页 -->
  <div class="newdetail">
    <van-nav-bar
      title="新闻资讯详细页"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 标题组件 -->
    <Title :title="newDetail.title"></Title>

    <!-- 主体内容 -->
    <article class="content" v-html="newDetail.content"></article>

    <!-- 评论区域 -->
    <Comment
      :total="total"
      :list="commentList"
      @loadingMore="moreComment"
      @publishFn="publish"
    ></Comment>
  </div>
</template>

<script>
import { getNewById } from "@/apis/newList";
import { getCommentsById, postCommentById } from "@/apis/comment.js";
import Title from "@/components/Title.vue";
import Comment from "@/components/Comment.vue";
export default {
  components: {
    Title,
    Comment,
  },
  data() {
    return {
      show: true,
      newDetail: [],
      commentList: [],
      total: 0,
      id: this.$route.params.id,
      pageindex: 1,
    };
  },
  async created() {
    //   获取图文资讯列表
    this.$nextTick(async () => {
      this.newDetail = (
        await getNewById(this.$route.params.id)
      ).data.message[0];
      //   console.log("this.newDetail", this.newDetail);
    });

    // 获取评论列表
    const res = await getCommentsById(this.$route.params.id, 1);
    // console.log("res", res);
    this.commentList = res.data.message.map((item) => {
      return {
        ...item,
        add_time: item.add_time.split("T")[0],
      };
    });
    // console.log("this.commentList", this.commentList);

    // 获取评论总数
    this.total = res.data.total;
  },
  methods: {
    //   点击更多评论
    moreComment() {
      this.pageindex += 1;
    },
    // 点击发表评论
    async publish(message) {
      //   console.log(typeof message);
      //   接收到的内容不为空
      if (message.length === 0) {
        return this.$toast.fail("评论内容不能为空");
      }
      const res = await postCommentById(this.id, `content= ${message}`);
      //   console.log(res);
      //   评论成功时
      if (res.data.message === "评论提交成功") {
        this.$toast.success(res.data.message);
        // 获取评论列表
        // 获取评论列表
        // 重置当前页码，重新获取数据
        this.pageindex = 1;
        const res1 = await getCommentsById(this.id, this.pageindex);
        // console.log("res1", res);
        this.commentList = res1.data.message.map((item) => {
          return {
            ...item,
            add_time: item.add_time.split("T")[0],
          };
        });
        // console.log("this.commentList", this.commentList);

        // 获取评论总数
        this.total = res1.data.total;
      }
    },
  },
  watch: {
    pageindex() {
      //   console.log(this.pageindex);
      getCommentsById(this.id, this.pageindex).then((res) => {
        // console.log("message", res.data.message);
        res.data.message.forEach((item) => {
          //   console.log(item);
          this.commentList.push(item);
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.van-nav-bar__content {
  background-color: #f7f7f7;
}
</style>
